<?php

	include_once ('ebuildy/functions.inc.php');
	
	date_default_timezone_set('UTC');
				
	class EbApplication
	{		
		// Instance of an EbDebug object
		// null means no debug
		static public $debug = null;
				
		static public $listFilters;
		static public $listDataSources;
		static public $commandEventMap;
	
		static public $instance;
		
		static public $metaData;
		
		public function __construct($defaultDataSource = null,$webConfigurationFile = null)
		{			
			$instance = $this;
											
			EbModel::$defaultDataSource = $defaultDataSource;
			
			if (!is_null(self::$debug))
			{
				self::$debug->beforeMemory = memory_get_usage();
			}
			
			//var_dump(EbModel::getModel("Core","UrlRoute")->create());die();
			
			if (is_null($webConfigurationFile))
			{
				$webConfigurationFile = EBUILDY_PATH.'cache/webConfiguration.inc.php';
			}
									
			include_once($webConfigurationFile);
			
			EbModel::init();
			EbView::init();
			EbController::init();
									
			/*if (!is_null(self::$debug))
			{
				error_reporting(-1);
			}
			else
			{
				error_reporting(-1);
			}*/
			
			
			
			$this->onRequestStart();
		}

		static public function getConfig($key,$default = null)
		{
			return isset(self::$metaData[$key]) ? self::$metaData[$key] : $default;
		}
		
		public function onSessionStart()
		{
		
		}
				
		public function onRequestStart()
		{
			try
			{						
				EbController::processRequest();			
			}
			catch(Exception $e)
			{
				$this->onError($e);
			}			
		}
		
		public function onError($e)
		{
			while (ob_get_level() > 0) ob_end_clean();
			
			if (is_file(ROOT.'/'.EbApplication::getConfig('errorTemplate')))
			{
				include ROOT.'/'.EbApplication::getConfig('errorTemplate');
			}
			else
			{
				include(EBUILDY_PATH.'template/ErrorTemplate.php');
			}
		}			
	}